import json
import logging
import os
from pathlib import Path

import requests
from xpinyin import Pinyin

from common import logger_config
from common.common_config import error_place_file
from graph.Graph import Graph
from history.History import History

logger_config.init_file_log()
logger_config.init_console_log()


class Search:
    def __init__(self,timeout=10) -> None:
        self.timeout =timeout

    def search(self, place_name, qry):
        post = requests.get(url="https://www.worldweatheronline.com/v2/search.ashx?qry=" + qry, timeout=self.timeout)
        text = post.text
        avg_url = ''
        history_url = ''
        if len(text) > 0:
            loads = json.loads(text)[0]
            place_name_by_search = loads['name'].replace(' ', '').strip().lower()
            if qry.lower() in place_name_by_search:
                logging.info(f'页面上搜索到的地名为{place_name_by_search},参与搜索的地名为{qry.lower()},匹配成功，开始爬取')
                avg_url = loads['url'].replace('weather', 'weather-averages')
                history_url = loads['url'].replace('weather', 'weather-history')
            else:
                logging.info(f'页面上搜索到的地名为{place_name_by_search},参与搜索的地名为{qry.lower()},匹配不上，该条爬取失败')
                self.write_error_place(place_name)
        else:
            logging.info(f'地名{place_name},参与搜索的地名为{qry.lower()},不存在，该条爬取失败')
            self.write_error_place(place_name)

        return avg_url, history_url

    def write_error_place(self, str_data):
        # 不存在就创建一个excel
        if not Path(error_place_file).exists():
            file = open(error_place_file, 'w')
            file.close()
        with open(error_place_file, 'a') as f:
            f.write(str_data + "\n")


if __name__ == '__main__':
    'gaoshan,fujian'
    search = Search()
    date = "2022-02-01"

    place_name = search.search("绍兴,浙江")
    avg_url, history_url = place_name
    h = History()
    viewstate = h.get_first_viewstate()
    url, viewstate, m = h.find(history_url, date, viewstate)
    history_path = '../output/zhejiang/history'
    my_file = Path(history_path)
    if not my_file.exists():
        os.makedirs(history_path)
    m.to_csv(f'{history_path}/{date}.csv')
    print(m)
    g = Graph()
    url, df_tuple_list = g.find(avg_url)
    for df_tuple in df_tuple_list:
        title, df = df_tuple
        title = title.replace(" ", '').replace(',', '')
        graph_path = '../output/zhejiang/shaoxing'
        my_file = Path(graph_path)
        if not my_file.exists():
            os.makedirs(graph_path)
        df.to_csv(f'{graph_path}/{title}.csv')
        print(df)
